<template>
  <div>
    <en-table-layout :tableData="tableData.data" :loading="loading" @selection-change="handleSelectionChange">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button size="mini" v-if="checkPermission(['purchasePlan:add'])" type="primary"
            @click="handleAddPurchasePlan">新增</el-button>
          <el-button size="mini" v-if="checkPermission(['purchasePlan:del'])" @click="handleDeletePurchasePlan()" type="danger"
            :disabled="multipleSelection.length === 0">删除</el-button>
        </div>
        <div class="toolbar-search">
          <en-table-search @search="searchEvent" @advancedSearch="advancedSearchEvent" placeholder="请输入计划编号" advanced
            advancedWidth="465">
            <template slot="advanced-content">
              <el-form ref="advancedForm" :model="advancedForm" label-width="90px">
                <el-form-item label="所属部门">
                  <el-cascader v-model="advancedForm.dept_id" :options="deptList" :props="{
                    label: 'name',
                    value: 'id',
                    emitPath: false,
                    checkStrictly: true
                  }" clearable></el-cascader>
                </el-form-item>
                <el-form-item label="时间">
                  <el-date-picker v-model="advancedForm.purchasePlan_time_range" type="daterange" align="center"
                    :editable="false" unlink-panels :clearable="false" :default-time="['00:00:00', '23:59:59']"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="timestamp"
                    :picker-options="{ disabledDate(time) { return time.getTime() - 1 >= new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime() + 86400000 - 1 }, shortcuts: MixinPickerShortcuts }">
                  </el-date-picker>
                </el-form-item>
              </el-form>
            </template>
          </en-table-search>
        </div>
      </div>

      <template slot="table-columns">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="sn" label="采购计划编号">
          <template slot-scope="scope">
            <router-link v-if="checkPermission(['purchasePlan'])" style="color: #409eff;" :to="{ name: 'purchasePlanDetail', params: { id: scope.row.id } }">{{
              scope.row.sn }}</router-link>
            <span v-else>{{scope.row.sn}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="编制日期">
          <template slot-scope="scope">{{ scope.row.formation_time | unixToDate }}</template>
        </el-table-column>
        <el-table-column prop="dept_name" label="所属部门" />
        <el-table-column prop="formation_person" label="编制人员" />
        <el-table-column prop="procurement_desc" label="采购说明" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" v-if="checkPermission(['purchasePlan:edit'])"
              @click="handleEditPurchasePlan(scope.row)">编辑</el-button>
            <el-button type="primary" v-if="checkPermission(['purchasePlan:print'])" size="mini"
              @click="handlePrintPurchasePlanDialog(scope.row)">打印</el-button>
          </template>
        </el-table-column>
      </template>

      <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[10, 20, 50, 100]"
        :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.data_total">
      </el-pagination>
    </en-table-layout>

    <el-dialog title="采购计划表" :visible.sync="dialogVisible" width="940px" center>
      <el-button size="mini" type="primary" @click="handlePrintPurchasePlan" class="print">打印</el-button>
      <div id="deliverySheet" style="width:900px">
        <div class="tips-t">
          <div>
            采购部门:{{ purchasePlanForm.dept_name }}
          </div>
          <div>
            计划编号:{{ purchasePlanForm.sn }}
          </div>
          <div>
            编制日期:{{ purchasePlanForm.formation_time | unixToDateStr }}
          </div>
        </div>
        <el-table :data="purchasePlanForm.product_list" border :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center', background: '#f4f4f4' }" style="width: 100%; margin-top: 20px;">
          <el-table-column label="序号">
            <template slot-scope="scope">
              {{ scope.row.product_id }}
            </template>
          </el-table-column>
          <el-table-column label="产品名称">
            <template slot-scope="scope">
              {{ scope.row.product_name }}
            </template>
          </el-table-column>
          <el-table-column label="规格型号">
            <template slot-scope="scope">
              {{ scope.row.specification }}
            </template>
          </el-table-column>
          <el-table-column label="数量">
            <template slot-scope="scope">
              {{ scope.row.procurement_num }}
            </template>
          </el-table-column>
          <el-table-column label="计划供应日期">
            <template slot-scope="scope" v-if="purchasePlanForm.supplier_time">
              {{ purchasePlanForm.supplier_time / 1000 | unixToDate }}
            </template>
          </el-table-column>
          <el-table-column label="备注">
            <template slot-scope="scope">
              {{ scope.row.remark }}
            </template>
          </el-table-column>
        </el-table>
        <div class="tips-f">
          采购说明:{{ purchasePlanForm.procurement_desc }}
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as API_Purchase from '@/api/purchase'
import Print from 'print-js'
import * as API_Setting from '@/api/setting'
import { Foundation } from '~/ui-utils'
export default {
  name: 'purchasePlan',
  data() {
    return {
      deptList: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10
      },
      // 高级搜索数据
      advancedForm: {},
      // 列表数据
      tableData: '',
      dialogVisible: false,
      // 当前已选择的行
      multipleSelection: [],
      purchasePlanForm: {}
    }
  },
  mounted() {
    this.GET_PurchasePlanList()
    this.GET_DeptList()
  },
  watch: {
    $route: function({ query }) {
      this.params.page_no = 1
      this.GET_PurchasePlanList()
    }
  },
  methods: {
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
      })
    },
    /** 打印对账详情 */
    handlePrintPurchasePlan() {
      Print({
        printable: 'deliverySheet',
        type: 'html',
        targetStyles: ['*'],
        ignoreElements: ['no-logs', 'goods-image', 'no-btn']
      })
    },
    handleDeletePurchasePlan() {
      this.$confirm('确定要删除这些采购计划吗？', '提示', { type: 'warning' }).then(() => {
        const ids = this.multipleSelection.map(item => item.id)
        API_Purchase.deletePurchasePlan(ids).then(() => {
          this.$message.success('删除成功！')
          this.params.page_no = 1
          this.GET_PurchasePlanList()
        })
      }).catch(() => { })
    },
    /** 多选改变 */
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_PurchasePlanList()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_PurchasePlanList()
    },

    /** 添加采购计划 */
    handleAddPurchasePlan() {
      this.$router.push({
        name: 'purchasePlanAdd',
        params: { callback: this.GET_PurchasePlanList }
      })
    },
    /** 添加采购计划 */
    handleEditPurchasePlan(row) {
      this.$router.push({
        name: 'purchasePlanEdit',
        params: { id: row.id }
      })
    },
    /** 打印采购计划 */
    handlePrintPurchasePlanDialog(row) {
      this.GET_PurchasePlanDetail(row.id)
    },
    /** 获取采购计划详情页面数据 */
    GET_PurchasePlanDetail(id) {
      API_Purchase.getPurchasePlanInfo(id).then(response => {
        this.purchasePlanForm = response
        this.dialogVisible = true
      })
    },
    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        sn: data
      }
      Object.keys(this.advancedForm).forEach((key) => delete this.params[key])
      this.params.page_no = 1
      this.GET_PurchasePlanList()
    },
    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm
      }
      delete this.params.start_time
      delete this.params.end_time
      if (this.advancedForm.purchasePlan_time_range) {
        this.params.start_time = parseInt(Number(this.advancedForm.purchasePlan_time_range[0]) / 1000)
        this.params.end_time = parseInt(Number(this.advancedForm.purchasePlan_time_range[1]) / 1000)
      }
      delete this.params.purchasePlan_time_range
      this.params.page_no = 1
      this.GET_PurchasePlanList()
    },
    /** 获取采购计划列表 */
    GET_PurchasePlanList() {
      this.loading = true
      API_Purchase.getPurchasePlanList(this.params).then(response => {
        this.loading = false
        this.tableData = response
      }).catch(() => { this.loading = false })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.print {
  margin-left: 790px;
}

.tips-t {
  display: flex;
  padding: 10px 0;

  div {
    flex: 1;
    text-align: center;
  }
}

.tips-f {
  padding: 20px 0;
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}
</style>
